<!--  -->
<template>
      <div>
        <a-card :bordered="false">
          <a-spin :spinning="spinning" :tip="spinningText">
          <f-search-form @searchHandler="searchHandler">
            <f-search-form-item label="专业包代码" name="majorCode" />
            <f-search-form-item label="专业包名称" name="majorName" />
            <f-search-form-item label="工程包代码" name="packageNo" />
            <f-search-form-item label="工程包名称" name="packageName" />
            <f-search-form-item label="物料wbs代码" name="materialWbsCode" slot="advanced" />
            <f-search-form-item label="物料code" name="materialCode"  slot="advanced" />
            <f-search-form-item label="设备材料名称" name="materialName" slot="advanced" />
            <f-search-form-item label="层级号" name="levelNo" slot="advanced" />
            <f-search-form-item label="科目名称" name="subjectName" slot="advanced" />
            <f-search-form-item label="区域" name="materialArea" slot="advanced" />
            <f-search-form-item label="系统" name="materialUse" slot="advanced" />
            <f-search-form-item label="历史版本" name="version" type="select" />
          </f-search-form>
<!--      <div style="margin-left: 60px">-->
<!--         <a-button type="button">批量导出</a-button>&nbsp;<a-button type="button" @click="save(dataSource)">提交</a-button>&nbsp;-->
<!--      </div>-->
      <f-table style="margin-top: 30px" ref="table" size="default" :multiple="false" :operator="operator"  rowKey="materialPlanId"  :columns="columns" :scroll="{x:1980,y:columns.length*40}" :params="queryParam" :api="api.materials" >
        <span slot="number" slot-scope="text, record">
          <a-tag color="#108ee9" @click="$refs.resum.handleShow(record)">{{ text }}</a-tag>
        </span>

        <template v-for="col in editSlots" :slot="col" slot-scope="text, record, index" :row-selection="rowSelection">
          <div :key="col">
            <a-date-picker  style="width: 100%"  v-if="editingKey=== record.materialPlanId&&col=='receivedDate'" value-format='YYYY-MM-DD' format='YYYY-MM-DD' type="date" v-model="receivedDate"  @change="handleChange(receivedDate,record.materialPlanId, col,record)" > </a-date-picker>
             <a-select  v-else-if ="editingKey=== record.materialPlanId&&col=='caseType'" style="width: 150px;" :filter-option="filterOption" showSearch="true" optionFilterProp="children"  v-model="caseType" @change="handleChange(caseType,record.materialPlanId, col,record)">
            <a-select-option  v-for ="item in dicList" :key="item.name" :value="item.name">
               {{item.name}}
            </a-select-option>
            </a-select>
            <a-select  v-else-if ="editingKey=== record.materialPlanId&&col=='vendorName'" style="width: 150px;" :filter-option="filterOption"  showSearch="true" optionFilterProp="children"    v-model="vendorName"   @change="handleChange(vendorName, record.materialPlanId, col,record)"  >
              <a-select-option  v-for ="item1 in supplierList" :key="item1.supplierName" :value="item1.supplierName" >
                {{item1.supplierName}}
              </a-select-option>
            </a-select>
            <a-input v-else-if="editingKey=== record.materialPlanId&&col=='purchaseCount'" style="margin: -5px 0" :value="text" @change="(e) => handleChange(e.target.value, record.materialPlanId, col,record)" />
            <a-input v-else-if="editingKey=== record.materialPlanId&&col=='technicalData'" style="margin: -5px 0" :value="text" @change="(e) => handleChange(e.target.value, record.materialPlanId, col,record)" />
            <a-input v-else-if="editingKey=== record.materialPlanId&&col=='brandName'" style="margin: -5px 0" :value="text" @change="(e) => handleChange(e.target.value, record.materialPlanId, col,record)" />
            <a-input v-else-if="editingKey=== record.materialPlanId&&col=='remark'" style="margin: -5px 0" :value="text" @change="(e) => handleChange(e.target.value, record.materialPlanId, col,record)" />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record,index">
          <template v-if="record.orderflg==='0'">
            <a @click="() => edit(record,record.materialPlanId)">申请数量</a>
          </template>
          <template v-if="record.orderflg==='1'">
            <a @click="() => edit(record,record.materialPlanId)">申请数量</a>
            <a @click="$refs.sun.handleShow(record)">订单下达</a>
          </template>
        </template>
<!--        <a-button type="button" @click="exportData(table)">导出</a-button>&nbsp;<a-button type="button" @click="save(dataSource)">提交</a-button>&nbsp;-->
      </f-table>
           <AlertPage ref="sun"></AlertPage>
           <resumeinquiry ref="resum"></resumeinquiry>
          <excel_application_list ref="excellist"  @excelTab="excelTab"></excel_application_list>
          <previewForSrmOpen ref="previewList" @previewOpen="previewOpen"></previewForSrmOpen>
          </a-spin>
          </a-card>
        <upload-modal ref="uploadModal" :action="api.materials.importPurseDetail" :otherParams="queryParam"
                      @change="uploadEnd"></upload-modal>
        <!-- <upload-modal ref="uploadProjectFile" :action="api.upFile.upFiles" :otherParams="projectFileParam"
                      @change="handleProjectFileChange" @on-before="beforeUploadProjectFile"></upload-modal> -->
        <a-row :key="fileKey">
          <a-modal ref="uploadProjectFile" v-model="uploadProjectFile">
            <a-upload-dragger
              name="file"
              :multiple="true"
              :action="api.upFile.upFiles"
              :headers="headers"
              :showUploadList="false"
              :data="{'projectId': projectId, 'uniqueFlag': uniqueFlag}"
              @change="handleProjectFileChange"
              :beforeUpload="beforeUploadProjectFile"
            >
              <a-button ref="uploadProjectFile" > <a-icon type="upload" /> 请选择需要上传的文件 </a-button>
            </a-upload-dragger>
          </a-modal>
        </a-row>
      </div>
</template>

<script>
  //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  //例如：import 《组件名称》 from '《组件路径》';
  import AlertPage from './alertpage'
  import resumeinquiry from './resumeinquiry'
  import api from '../../material/app/js/api'
  import Excel_application_list from './excel_application_list'
  import previewForSrmOpen from './preview_for_srm_open'
  import { formatDecimals } from '../../business/common/data'
  import Vue from 'vue'
  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
      previewForSrmOpen,
      Excel_application_list,
      AlertPage,
      resumeinquiry
    },
    props: {
      detailsParams: {},
      projectStatus: {
        type: String,
        default: ''
      }
    },
    data() {
      //这里存放数据
      let operator = []
      operator.push({
        name: '导出',
        icon: 'export',
        that: this,
        handler: function (table, that) {
          that.detailsParams.majorCode = table.parameter.majorCode
          that.detailsParams.majorName = table.parameter.majorName
          that.detailsParams.packageNo = table.parameter.packageNo
          that.detailsParams.packageName = table.parameter.packageName
          that.detailsParams.materialWbsCode = table.parameter.materialWbsCode
          that.detailsParams.materialCode = table.parameter.materialCode
          that.detailsParams.materialName = table.parameter.materialName
          that.detailsParams.levelNo = table.parameter.levelNo
          that.detailsParams.subjectName = table.parameter.subjectName
          that.detailsParams.materialArea = table.parameter.materialArea
          that.detailsParams.materialUse = table.parameter.materialUse
          that.exportData()
        }
      })
      operator.push({
        name: '提交',
        icon: 'import',
        that: this,
        handler: function (table, that) {
          if (that.projectStatus === 1) {
            that.$message.error('项目已锁定不支持操作')
            return
          }
          //提示是否需要上传文件
          that.$confirm({
            content: '是否需要上传附件？',
            onOk() {
              that.spinning = false
              that.uploadProjectFile = true
              that.fileKey = Math.random();
            },
            cancelText: '否，直接提交',
            closable: false,
            okText: '是',
            onCancel() {
              that.spinning = false
              that.uploadProjectFile = false
              that.save(that.dataSource)
              that.$refs.table.refresh()
              that.editingKey = ''
            }
          })
        }
      })
      operator.push({
        name: '导入数据',
        icon: 'import',
        that: this,
        handler: function (table, that) {
          if (that.projectStatus === 1) {
            that.$message.error('项目已锁定不支持操作')
            return
          }
          that.$refs.uploadModal.open()
        }
      })
      operator.push({
        name: '开口订单下达',
        icon: '',
        that: this,
        handler: function(table, that) {
          that.$refs['previewList'].handleShow(that.detailsParams)
        }
      })
      const token = Vue.ls.get('Access-Token')
      return {
        headers: { 'Authorization': token },
        api: Object.assign(api, this.api),
        //列表初始化查询参数
        queryParam: {},
        flag: false,
        modalVisible: false,
        uploadProjectFile: false,
        uploadFileCount: 0,
        fileKey: '1231',
        editingKey: '',
        scorykey: '',
        supplierId: '',
        value: '',
        caseType: '',
        vendorName: '',
        receivedDate: '',
        uniqueFlag: '',
        code: '',
        dicList: [],
        projectFileParam: {},
        spinningText: '文件导入中，请稍后...',
        spinning: false,
        columns: [{
          title: '编号',
          align: 'center',
          width: 100,
          dataIndex: 'materialPlanId',
          scopedSlots: {
            customRender: 'materialPlanId'
          }
        },
          {
            title: '工程包名称',
            align: 'center',
            width: 100,
            dataIndex: 'packageName',
            scopedSlots: {
              customRender: 'packageName'
            }
          },
          {
            title: '工程包代码',
            align: 'center',
            width: 100,
            dataIndex: 'packageNo',
            scopedSlots: {
              customRender: 'packageNo'
            }
          },
          {
            title: '专业包名称',
            align: 'center',
            width: 100,
            dataIndex: 'majorName',
            scopedSlots: {
              customRender: 'majorName'
            }
          },
          {
            title: '专业包代码',
            align: 'center',
            width: 100,
            dataIndex: 'majorCode',
            scopedSlots: {
              customRender: 'majorCode'
            }
          },
          {
            title: '物料代码',
            align: 'center',
            width: 100,
            dataIndex: 'materialCode',
            scopedSlots: {
              customRender: 'materialCode'
            }
          },
          {
            title: 'WBS代码',
            align: 'center',
            width: 100,
            dataIndex: 'materialWbsCode',
            scopedSlots: {
              customRender: 'materialWbsCode'
            }
          },

          {
            title: '设备、材料名称',
            align: 'center',
            width: 200,
            dataIndex: 'materialName',
            scopedSlots: {
              customRender: 'materialName'
            }
          },
          // {
          //   title: '型号/规格',
          //   align: 'center',
          //   width: 200,
          //   dataIndex: 'materiaSpecs',
          //   scopedSlots: {
          //     customRender: 'materiaSpecs'
          //   }
          // },
          {
            title: '项目名称',
            align: 'center',
            width: 200,
            dataIndex: 'materiaSpecs',
            scopedSlots: {
              customRender: 'materiaSpecs'
            }
          },
          {
            title: '层级号',
            align: 'center',
            width: 100,
            dataIndex: 'levelNo',
            scopedSlots: {
              customRender: 'levelNo'
            }
          },
          {
            title: '区域',
            align: 'center',
            width: 100,
            dataIndex: 'materialArea',
            scopedSlots: {
              customRender: 'materialArea'
            }
          },
          {
            title: '系统',
            align: 'center',
            width: 100,
            dataIndex: 'materialUse',
            scopedSlots: {
              customRender: 'materialUse'
            }
          },
          {
            title: '计量单位',
            align: 'center',
            width: 100,
            dataIndex: 'measurementUnit',
            scopedSlots: {
              customRender: 'measurementUnit'
            }
          },
          {
            title: '物料单位',
            align: 'center',
            width: 100,
            dataIndex: 'materialDescSrm'
          },
          // {
          //   title: '换算单位',
          //   align: 'center',
          //   width: 190,
          //   dataIndex: 'conversionUnit',
          //   scopedSlots: {
          //     customRender: 'conversionUnit'
          //   }
          // },
          // {
          //   title: '100工程量计量单位合计',
          //   align: 'center',
          //   width: 190,
          //   dataIndex: 'unitBillQuantity100',
          //   scopedSlots: {
          //     customRender: 'unitBillQuantity100'
          //   }
          // },
          // {
          //   title: '100工程量换算单位合计',
          //   align: 'center',
          //   width: 190,
          //   dataIndex: 'convertBillQuantity100',
          //   scopedSlots: {
          //     customRender: 'convertBillQuantity100'
          //   }
          // },
          // {
          //   title: '200工程量计量单位合计',
          //   align: 'center',
          //   width: 190,
          //   dataIndex: 'unitBillQuantity200',
          //   scopedSlots: {
          //     customRender: 'unitBillQuantity200'
          //   }
          // },
          // {
          //   title: '200工程量换算单位合计',
          //   align: 'center',
          //   width: 190,
          //   dataIndex: 'convertBillQuantity200',
          //   scopedSlots: {
          //     customRender: 'convertBillQuantity200'
          //   }
          // },
          {
            title: '100预算工程量',
            align: 'center',
            width: 150,
            dataIndex: 'costQuantity100',
            scopedSlots: {
              customRender: 'costQuantity100'
            }
          },
          {
            title: '200预算工程量',
            align: 'center',
            width: 150,
            dataIndex: 'costQuantity200',
            scopedSlots: {
              customRender: 'costQuantity200'
            }
          },
          {
            title: '损耗率',
            align: 'center',
            width: 100,
            dataIndex: 'loss',
            scopedSlots: {
              customRender: 'loss'
            }
          },
          {
            title: '采购计划量',
            align: 'center',
            width: 100,
            dataIndex: 'planPurchaseCount',
            scopedSlots: {
              customRender: 'planPurchaseCount'
            }
          },
          // {
          //   title: '采购计划量换算单位合计',
          //   align: 'center',
          //   width: 190,
          //   dataIndex: 'convertPurchaseCount',
          //   scopedSlots: {
          //     customRender: 'convertPurchaseCount'
          //   }
          // },
          {
            title: '在途',
            align: 'center',
            width: 100,
            dataIndex: 'ztPurchaseCount',
            scopedSlots: {
              customRender: 'ztPurchaseCount'
            }
          },
          {
            title: '到货',
            align: 'center',
            width: 100,
            dataIndex: 'dhPurchaseCount',
            scopedSlots: {
              customRender: 'dhPurchaseCount'
            }
          },
          {
            title: '本次采购量',
            align: 'center',
            width: 100,
            dataIndex: 'purchaseCount',
            scopedSlots: {
              customRender: 'purchaseCount'
            }
          },
          {
            title: '计划到货时间',
            align: 'center',
            width: 200,
            dataIndex: 'receivedDate',
            scopedSlots: {
              customRender: 'receivedDate'
            }

          },
          {
            title: '单据类型',
            align: 'center',
            width: 180,
            dataIndex: 'caseType',
            scopedSlots: {
              customRender: 'caseType'
            }
          },
          {
            title: '班组',
            align: 'center',
            width: 180,
            dataIndex: 'vendorName',
            scopedSlots: {
              customRender: 'vendorName'
            }
          },
          {
            title: '剩余采购量',
            align: 'center',
            width: 100,
            dataIndex: 'endPurchaseCount',
            scopedSlots: {
              customRender: 'endPurchaseCount'
            }
          },
          {
            title: '技术参数或技术说明',
            align: 'center',
            width: 200,
            dataIndex: 'technicalData',
            scopedSlots: {
              customRender: 'technicalData'
            }
          },
          {
            title: '品牌',
            align: 'center',
            width: 200,
            dataIndex: 'brandName',
            scopedSlots: {
              customRender: 'brandName'
            }
          },
          {
            title: '备注',
            align: 'center',
            width: 100,
            dataIndex: 'remark',
            scopedSlots: {
              customRender: 'remark'
            }
          },
          {
            title: '操作',
            align: 'center',
            dataIndex: 'orderflg',
            width: 100,
            scopedSlots: {
              customRender: 'operation'
            }
          }
        ],
        operator: operator,
        dataSource: [],
        dataValue: {},
        supplierList: [],
        editSlots: ['purchaseCount', 'receivedDate', 'caseType', 'vendorName','technicalData','brandName'],
        version: '',
        projectId: '',
        propTableData: {
          sel: null, // 选中行
          col: []
        },
        data: []
      }
      // const cacheData = this.dataSource.map(item => ({ ...item }))
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      handleProjectFileChange: function(info,file) {
        if (info.file.status === 'done') {
          this.spinning = false
          if (info.file.response.code === 100) {
            debugger
            this.uploadFileCount = this.uploadFileCount+1
            if(this.uploadFileCount === info.fileList.length) {
              this.uploadProjectFile = false
              this.uploadFileCount = 0
              this.save(this.dataSource)
            }
          } else {
            this.$message.error(info.file.response.message)
          }
        } else if (info.file.status === 'error') {
          this.uploadProjectFile = false
          this.uploadFileCount = 0
          this.$message.error('导入失败')
        }
      },
      beforeUploadProjectFile: function() {
        this.spinningText = '文件导入中，请稍后...'
        this.spinning = true
        this.uniqueFlag = this.getRandom()
        return true
      },
      getRandom: function () {
        const arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
        let num = ""
        for(var i = 0; i < 32; i++) {
          num += arr[parseInt(Math.random() * 36)];
        }
        return num;
      },
      //批量导出
      exportData() {
        if (this.projectStatus === 1) {
          this.$message.error('项目已锁定不支持操作')
             return
        }
        // let selectIds = this.$refs.table.getSelectedRowKey()
        // if (!selectIds || selectIds.length === 0) {
        //   this.$message.error('您还未选中数据')
        //   return
        // }
         let that = this
         let columns = this.$refs.table.getExportColumns(that.columns)
          columns.push({ name: '是否修改', key: 'isUpdate' })
          that.detailsParams['columns'] = JSON.stringify(columns)
        // this.queryParam['materialPlanIds'] = selectIds.join(',')
         that.http.exportExcel(that, {
          url: that.api.materials.exportUrl,
          data: that.detailsParams
        })
      },

      // handleShow(data) {
      //   this.isEdit = false
      //   this.queryParam.projectId = data.projectId
      //   this.queryParam.version = data.bigVersion
      //
      //   let queryParam = {...this.detailsParams}
      //   this.queryParam['projectId'] = data.projectId
      //   this.queryParam['version'] = data.bigVersion
      //   if (data) {
      //     this.isEdit = true
      //   }
      //   this.modalVisible = true
      //   this.$refs.table.refresh()
      // },
      // handleClose() {
      //   //this.$refs[this.current].handleReset()npm run s
      //   this.modalVisible = false
      // },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.indexOf(input) >= 0
        )
      },
      handleChange(value, key, column, record) {
        const newData = [...this.dataSource]
        const target = newData.filter((item) => key === item.materialPlanId)[0]
        record[column] = value
        if (target != undefined && target) {
          target[column] = value
          target['materialCode'] = record['materialCode']
          target['materialWbsCode'] = record['materialWbsCode']
          this.dataSource = newData
        } else {
          const newData2 = {}
          newData2.materialPlanId = key
          newData2[column] = value
          newData2['materialCode'] = record['materialCode']
          newData2['materialWbsCode'] = record['materialWbsCode']
          this.dataSource.push(newData2)
        }
      },
      edit(record, key) {
        this.receivedDate = ''
        this.caseType = ''
        this.vendorName = ''
        if (this.editingKey === key) {
          this.editingKey = ''
        } else {
          if(record['measurementUnit'] !== record['materialDescSrm']) {
            this.$message.error('计量单位与物料单位不一致！')
            return
          }
          this.editingKey = key
        }
      },
      save(dataSource) {
        if (this.projectStatus === 1) {
          this.$message.error('项目已锁定不支持操作')
          return
        }
        const jsonData = JSON.stringify(dataSource)
        const projectIds = this.queryParam.projectId
        const versionIds = this.queryParam.version
        const uniqueFlag = this.uniqueFlag
        this.spinning = true
        this.spinningText = '数据提交中，请稍后...'
        this.http.post(this, {
          url: this.api.materials.applyPurchase,
          data: {
            dataArray: jsonData,
            projectId: projectIds,
            versionId: versionIds,
            uniqueFlag: uniqueFlag
          },
          success: function (me, data) {
            me.spinning = false
            me.$message.success('操作成功')
            me.$refs.table.refresh()
            me.editingKey = ''
          },
          error: function (me, data) {
            me.spinning = false
          }
        })
      },
      cancel(key) {
        const newData = [...this.dataSource]
        const target = newData.filter((item) => key === item.key)[0]
        this.editingKey = ''
        if (target) {
          delete target.editable
          this.dataSource = newData
        }
      },
      excelTab() {
        this.$refs.table.refresh()
      },
      previewOpen() {
        this.$refs.table.refresh()
      },
      uploadEnd(url,file) {
        var  excelkey = file.response.data
        var projectid = this.queryParam.projectId
        var version = this.queryParam.version
        this.$refs.uploadModal.close()
        this.$refs['excellist'].handleShow(excelkey , projectid ,version)
      }
      // handleSearch(value) {
      //   debugger
      //   fetch(value, supplierList => (this.supplierList = supplierList))
      // }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      let queryParam = {...this.detailsParams}
      this.projectId = queryParam.projectId
      this.queryParam['projectId'] = queryParam.projectId
      this.queryParam['version'] = queryParam.version
      this.projectFileParam['projectId'] = queryParam.projectId
      this.spinning = false
      this.uploadProjectFile = false
      this.http.get(this, {
        url: this.api.purchases.getCaseTypeDate,
        data: {
          docTypes: 'docTypes'
        },
        success: function (me, data) {
          me.dicList = data
        }
      })
      this.http.get(this, {
        url: this.api.purchases.getallSupplier,
        data: {
          docTypes: 'docTypes'
        },
        success: function (me, data) {
          me.supplierList = data
        }
      })
    },
    filters: {
      format(num) {
        return formatDecimals(num, 3)
      }
    }
  }
</script>

<style lang="scss" scoped>
  //@import url(); 引入公共css类
</style>
